import { FETCH_WEATHER, REMOVE_CITY_FROM_WEATHER_LIST } from '../actions/weather';

export default function(state = [], action) {
  // console.log('Action received ', action);
  switch (action.type) {
    case FETCH_WEATHER:
      // return state.concat([ action.payload.data ]);
      // return state.push(action.payload.data);
      let existIndex;
      let newItem = action.payload.data;
      for (var i = 0; i < state.length; i++) {
        let item = state[i];
        if(item.city.id === newItem.city.id) {
          state[i] = action.payload.data;
          return state;
        }
      }
      return [action.payload.data, ...state];
      break;
    case REMOVE_CITY_FROM_WEATHER_LIST:
      return state.filter( (item) => {
        return item.city.id !== action.payload.city.id
      });
      break;
  }
  return state;
}
